package net.framework.smc.kotlin.demokotlin.config

import org.apache.kafka.clients.producer.ProducerConfig
import org.apache.kafka.common.serialization.StringSerializer
import org.springframework.beans.factory.annotation.Value
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.kafka.annotation.EnableKafka
import org.springframework.kafka.core.DefaultKafkaProducerFactory
import org.springframework.kafka.core.KafkaTemplate
import org.springframework.kafka.core.ProducerFactory

/**
 *  @authore zyx
 *  @date 2018/7/5 17:28
 */
@Configuration
@EnableKafka
class KafkaConfig {

    @Value("\${kafka.producer.servers}")
    lateinit var servers: String

    @Value("\${kafka.producer.retries}")
    var retries: Int = 0

    @Value("\${kafka.producer.batch.size}")
    var batchSize: Int = 0

    @Value("\${kafka.producer.linger}")
    var linger : Int = 0

    @Value("\${kafka.producer.buffer.memory}")
    var bufferMemory : Int = 0

    fun producerConfigs() : Map<String, Any>{
        var props = HashMap<String, Any>()
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, servers)
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, servers)
        props.put(ProducerConfig.RETRIES_CONFIG, retries)
        props.put(ProducerConfig.BATCH_SIZE_CONFIG, batchSize)
        props.put(ProducerConfig.LINGER_MS_CONFIG, linger)
        props.put(ProducerConfig.BUFFER_MEMORY_CONFIG, bufferMemory)
        props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer")
        props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer")
        return props
    }

    fun producerFactory(): ProducerFactory<String, String> {
        return DefaultKafkaProducerFactory<String, String>(producerConfigs())
    }

    @Bean
    fun kafkaTemplate(): KafkaTemplate<String, String>{
        return KafkaTemplate<String, String>(producerFactory())
    }

}